package org.sunflower.util.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadUtils {
	//创建一个可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲线程，若无可回收，则新建线程
	static ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); 
	//创建一个定长线程池，可控制线程最大并发数，超出的线程会在队列中等待
	static ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(3); 
	//创建一个定长线程池，支持定时及周期性任务执行
	static ExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(3); 
	//创建一个单线程化的线程池，它只会用唯一的工作线程来执行任务，保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行
	static ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor(); 
	public static void main(String[] args) {
		//创建一个可缓存线程池
		runHandle(cachedThreadPool,"1-cachedThreadPool");
		cachedThreadPool.shutdown();
		System.out.println("--------------------------可缓存线程池关闭--------------------------");
		
		//创建一个定长线程池
		runHandle(newFixedThreadPool,"2-newFixedThreadPool");
		newFixedThreadPool.shutdown();
		System.out.println("--------------------------定长线程池（可控制线程最大并发数）关闭--------------------------");
		
		//创建一个定长线程池
		runHandle(newScheduledThreadPool,"3-newScheduledThreadPool");
		newScheduledThreadPool.shutdown();
		System.out.println("--------------------------定长线程池（支持定时及周期性任务执行）关闭--------------------------");
		
		//创建一个单线程化的线程池
		runHandle(newSingleThreadExecutor,"4-newSingleThreadExecutor");
		newSingleThreadExecutor.shutdown();
		System.out.println("--------------------------单线程化的线程池关闭--------------------------");
	}
	
	public static void runHandle(ExecutorService threadPool,String threadPoolType){
		List<Future<String>> list = new ArrayList<Future<String>>();
		for(int i=0;i<30;i++){
//			TreadHandle task = TreadHandle.getTreadHandle(i,threadPoolType);
			TreadHandle task = new TreadHandle(i,threadPoolType);
			Future<String> reslut = threadPool.submit(task);
			list.add(reslut);
		}
		System.gc();
		for(Future<String> reslut:list){
			try {
				System.out.println(reslut.get());
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
	}
}
